<template>
  <div class="header-search" :class="{ isShow: show }">
    <svg-icon class-name="search-icon" icon="search" @click.stop="toggleShow" />
    <el-select
      class="header-el-search"
      v-model="search"
      placeholder="请输入关键字"
      filterable
      remote
      default-first-option
      popper-class="header-search-select"
      :remote-method="remoteMethod"
      @change="onSelectChange"
    >
      <el-option
        v-for="option in searchOptions"
        :key="option.item.path"
        :label="option.item.title.join(' > ')"
        :value="option.item"
      ></el-option>
    </el-select>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { filterRoutes } from '@/utils/route'
import { generateRoutes } from './fuse-data'
import { useRouter } from 'vue-router'
import Fuse from 'fuse.js'
const router = useRouter()
// 获取routes数据源
const searchPool = computed(() => {
  const filterRouteList = filterRoutes(router.getRoutes())
  return generateRoutes(filterRouteList)
})

// searchOptions数据
const searchOptions = ref([])

const fuse = new Fuse(searchPool.value, {
  // 是否按优先级进行排序
  shouldSort: true,
  // 匹配长度超过这个值的才会被认为是匹配的
  minMatchCharLength: 1,
  // 将被搜索的键列表。这支持嵌套路径、加权搜索、在字符串和对象数组中搜索。
  // name:搜索的键
  // weight:对应的权重
  keys: [
    {
      name: 'title',
      weight: 0.7
    },
    {
      name: 'path',
      weight: 0.3
    }
  ]
})
// 搜索关键字
const search = ref('')
// 是否展示搜索框
const show = ref(false)
const remoteMethod = (query) => {
  if (query.length <= 0) {
    searchOptions.value = []
  } else {
    searchOptions.value = fuse.search(query)
  }
}
const onSelectChange = ({ path }) => {
  router.push(path)
}
const toggleShow = () => {
  show.value = !show.value
}

watch(show, (val) => {
  if (val) {
    document.addEventListener('click', closed)
  } else {
    document.removeEventListener('click', closed)
  }
})
const closed = () => {
  show.value = false
  searchOptions.value = []
  search.value = ''
}
</script>

<style lang="scss" scoped>
.header-search {
  @include flex-center;
  ::v-deep .search-icon {
    font-size: 22px;
  }
  .header-el-search {
    width: 0;
    overflow: hidden;
    transition: width 0.4s ease-in-out;
    ::v-deep .el-input__inner {
      border-top: none;
      border-left: none;
      border-right: none;
    }
  }
  &.isShow {
    .header-el-search {
      width: 215px;
    }
  }
}
</style>

<style lang="scss">
.header-search-select {
  .el-select-dropdown__item {
    color: #3a8ee6 !important;
  }
}
</style>
